package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by admin on 2019/8/13.
 */
@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyCommentRepository repository;


    @Override
    public void saveOrUpdate(StrategyComment comment) {

        if (!StringUtils.hasLength(comment.getId())) {
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }


    @Override
    public Page query(StrategyCommentQuery qo) {

        Query query = new Query();
        if (qo.getDetailId() != -1) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }

        long count = template.count(query, StrategyComment.class);
        if (count == 0) {
            return Page.empty();
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.by(Sort.Direction.DESC, "createTime"));

        query.with(pageable);

        List<StrategyComment> list = template.find(query, StrategyComment.class);

        return new PageImpl(list, pageable, count);
    }

    @Override
    public void commentThumbUp(String toid, Long fromid) {

        Optional<StrategyComment> optional = repository.findById(toid);
        StrategyComment comment = optional.get();
        if (comment != null) {
            List<Long> thumbuplist = comment.getThumbuplist();
            if (thumbuplist.contains(fromid)) {
                // 取消点赞
                comment.setThumbupnum(comment.getThumbupnum() - 1);
                thumbuplist.remove(fromid);
            } else {
                // 点赞
                comment.setThumbupnum(comment.getThumbupnum() + 1);
                thumbuplist.add(fromid);
            }
        }
        repository.save(comment);
    }
}
